using Core;
using UnityEngine;

namespace g_gongjianta
{
    public class BulletMoveComponent : UnitComponent<Bullet>, IUpdate
    {
        private float initialSpeed = 15f; // 初始速度
        private float gravity = 9.8f; // 自定义重力系数（可调大实现更明显下坠）
        private float rotationSmoothness = 5f; // 转向平滑系数

        private Vector2 velocity; // 当前速度向量
        // private bool isFlying = false; // 飞行状态标识

        public bool Enable { get; private set; }

        public override void Awake()
        {
            base.Awake();

            Enable = true;

            var bowAngle = Unit.transform.eulerAngles.z;
            var angleRadians = bowAngle * Mathf.Deg2Rad;
            var launchDirection = new Vector2(
                Mathf.Cos(angleRadians),
                Mathf.Sin(angleRadians)
            );

            velocity = launchDirection * initialSpeed;
        }

        public override void Dispose()
        {
            if (IsDisposed) return;

            base.Dispose();
        }

        public void Update()
        {
            if (Enable == false) return;

            // 应用重力影响
            velocity.y -= gravity * Time.deltaTime;
            // 更新位置
            var pos = Unit.transform.position;
            pos += (Vector3)velocity * Time.deltaTime;
            Unit.transform.position = pos;
            RotateToVelocity();

            // 如果子弹落地，销毁子弹
            if (pos.y < 0)
            {
                Enable = false;
                Unit.Main.Interrupt();
            }
        }

        // 根据速度方向旋转箭矢
        private void RotateToVelocity()
        {
            if (velocity == Vector2.zero) return;

            // 计算目标角度
            float targetAngle = Mathf.Atan2(velocity.y, velocity.x) * Mathf.Rad2Deg;

            // 平滑旋转（使用 Lerp 避免突变）
            var targetRotation = Quaternion.Euler(0, 0, targetAngle);
            Unit.transform.rotation = Quaternion.Lerp(
                Unit.transform.rotation,
                targetRotation,
                rotationSmoothness * Time.deltaTime
            );
        }
    }
}